<template>
  <div class="code-demo">
    <!-- 演示区域 -->
    <div class="demo-showcase">
      <slot name="demo"></slot>
    </div>
    
    <!-- 操作栏 -->
    <div class="demo-actions">
      <button 
        class="action-button"
        @click="toggleCode"
        :class="{ active: showCode }"
      >
        <img class="action-icon" :src="`/icons/${showCode ? 'un' : ''}expand.svg`"/>
      </button>
      
      <button 
        class="action-button copy-button"
        @click="copyCode"
        
      >
        <svg focusable="false" data-icon="snippets" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M832 112H724V72c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v40H500V72c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v40H320c-17.7 0-32 14.3-32 32v120h-96c-17.7 0-32 14.3-32 32v632c0 17.7 14.3 32 32 32h512c17.7 0 32-14.3 32-32v-96h96c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zM664 888H232V336h218v174c0 22.1 17.9 40 40 40h174v338zm0-402H514V336h.2L664 485.8v.2zm128 274h-56V456L544 264H360v-80h68v32c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-32h152v32c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-32h68v576z"></path></svg>
      </button>
    </div>
    
    <!-- 代码区域 -->
    <Transition name="code-slide">
      <div v-show="showCode" class="demo-code">
        <slot name="code"></slot>
        <!-- 底部隐藏按钮 -->
        <div class="demo-code-footer">
          <button class="hide-code-button" @click="toggleCode">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/>
            </svg>
            隐藏代码
          </button>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

interface Props {
  title?: string;
  description?: string;
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  description: ''
});

const showCode = ref(false);
const copied = ref(false);

const toggleCode = () => {
  showCode.value = !showCode.value;
};

const copyCode = async () => {
  try {
    const codeElement = document.querySelector('.demo-code pre code');
    if (codeElement) {
      await navigator.clipboard.writeText(codeElement.textContent || '');
      copied.value = true;
      setTimeout(() => {
        copied.value = false;
      }, 2000);
    }
  } catch (err) {
    console.error('复制失败:', err);
  }
};
</script>